package com.mall4j.cloud.search.config;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.security.InvalidParameterException;
import java.util.List;

/**
 * @author FrozenWatermelon
 * @date 2020/9/24
 */
@Configuration
public class ElasticConfig {

    @Bean
    @ConditionalOnMissingBean(RestHighLevelClient.class)
    public RestHighLevelClient restHighLevelClient(ElasticsearchProperties elasticsearchProperties) {
        List<String> esConnectUrlList = elasticsearchProperties.getUris();
        if (CollectionUtils.isEmpty(esConnectUrlList)) {
            throw new InvalidParameterException("elasticsearch连接参数配置缺失");
        }
        RestHighLevelClient restClient = new RestHighLevelClient(RestClient.builder(HttpHost.create(CollectionUtil.getFirst(esConnectUrlList))));
        return restClient;
    }
}
